<?php

namespace hangpu8\hpcms\service;

use think\exception\ValidateException;
use thans\jwt\facade\JWTAuth;
use think\Exception;

class Login
{
    /**
     * 系统登录
     *
     * @param string $username
     * @param string $password
     * @return string
     */
    public function login(string $username, string $password)
    {
        $model = new \hangpu8\hpcms\model\Admin;
        $post = [
            'username'          => $username,
            'password'          => $password
        ];
        validate(\hangpu8\hpcms\validate\Admin::class)
            ->scene('login')
            ->check($post);
        $post['password'] = md5($password);
        $user = $model->where($post)->find();
        if (!$user) {
            throw new Exception("404\r\n账号或密码错误");
        }
        if ($user->status == 0) {
            throw new Exception("404\r\n该账号已被封禁");
        }
        // 生成登录标识
        $data = [
            'id'            => $user->id,
            'role_id'       => $user->role_id,
            'nickname'      => $user->nickname,
            'username'      => $user->username,
            'headimg'       => $user->headimg,
        ];
        $token = JWTAuth::builder($data);

        // 返回数据
        return $token;
    }

    /**
     * 获取登录的管理员信息
     *
     * @return array
     */
    public function getLoginInfo(): array
    {
        $Authorization = request()->header('Authorization');
        if (empty($Authorization)) {
            throw new Exception("请提供登录令牌", 404);
        }
        $payload = JWTAuth::auth();
        $id = $payload['id']->getValue();
        $role_id = $payload['role_id']->getValue();
        $username = $payload['username']->getValue();
        $nickname = $payload['nickname']->getValue();
        $headimg = $payload['headimg']->getValue();

        // 查询角色
        $levelDb = new \hangpu8\hpcms\model\AdminRole;
        $level = $levelDb->where(['id' => $role_id])->find();
        if (!$level) {
            throw new Exception("该管理员无角色等级");
        }
        $data = [
            'uid'               => $id,
            'role_id'           => $role_id,
            'username'          => $username,
            'nickname'          => $nickname,
            'headimg'           => $headimg,
            'level'             => $level->title,
        ];
        return $data;
    }
}
